package crud

import (
	"os"
)

var mTempl = `<?php
namespace {{.__NAMESPACE__}};

use laytp\BaseModel;
use app\model\Member;
use app\model\admin\custom\Books;
use app\model\admin\custom\Levels;
use app\model\admin\custom\Order;
use think\model\concern\SoftDelete;

class {{.__CLASS__}} extends BaseModel
{
	{{.__SOFT_DELETE__}}

    //模型名
    protected $name = '{{.__TABLE__}}';

    //附加属性
    protected $append = [];

    //时间戳字段转换
    protected $type = [
	];

	{{.__USER__}}

	{{.__BOOK__}}

	{{.__LEVEL__}}

	{{.__ORDER__}}

}`

// 生成控制器
func (g *cGlobal) MakeModel() error {
	err := os.MkdirAll(g.AppPath.ModelPath, os.ModePerm)
	if err != nil {
		return err
	}

	__USER__ := ""
	if g.Field != nil {
		if _, ok := g.Field["user_id"]; ok {
			__USER__ = `
				public function Members() {
                    return $this->hasOne(Member::class, 'id', 'user_id')->field('id, nickname, realname, mobile');
                }`
		}
	}
	__BOOK__ := ""
	if g.Field != nil {
		if _, ok := g.Field["book_id"]; ok {
			__BOOK__ = `
				public function Books() {
			        return $this->hasOne(Books::class, 'id', 'book_id')->field('id, category_name, name, wordsCount, level_id, level_name');
			    }`
		}
	}
	__LEVEL__ := ""
	if g.Field != nil {
		if _, ok := g.Field["level_id"]; ok {
			__LEVEL__ = `
				public function Levels() {
			        return $this->hasOne(Levels::class, 'id', 'level_id')->field('id, name');
			    }`
		}
	}
	__ORDER__ := ""
	if g.Field != nil {
		if _, ok := g.Field["order_id"]; ok {
			__LEVEL__ = `
				public function Orders() {
			        return $this->hasOne(Order::class, 'id', 'order_id')->field('id, order_no');
			    }`
		}
	}
	__SOFT_DELETE__ := ""
	if g.Field != nil {
		if _, ok := g.Field["delete_time"]; ok {
			__SOFT_DELETE__ = `use SoftDelete;`
		}
	}

	m := map[string]string{
		"__NAMESPACE__":   g.NameSpace.Model,
		"__CLASS__":       g.Class,
		"__USER__":        __USER__,
		"__BOOK__":        __BOOK__,
		"__LEVEL__":       __LEVEL__,
		"__ORDER__":       __ORDER__,
		"__SOFT_DELETE__": __SOFT_DELETE__,
		"__TABLE__":       g.TableName,
	}

	err = TemplateExec(g.AppFiles.Model, mTempl, m)
	if err != nil {
		return err
	}

	return nil
}
